package com.ea.report.service.impl;

import cn.hutool.core.util.IdUtil;
import com.ea.common.SA.pojo.dto.VideoAnalyzeInfo;
import com.ea.common.SA.pojo.entity.VideoFileMeta;
import com.ea.report.service.SAService;
import com.ea.report.service.StorageService;
import org.apache.commons.io.FilenameUtils;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@Service
public class SAServiceImpl implements SAService {

    private final StorageService storageService;

    @Autowired
    private Queue vibraQueue;

    @Autowired
    private Queue shenshiQueue;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @Autowired
    public SAServiceImpl(StorageService storageService) {
        this.storageService = storageService;
    }

    /**
     *
     * @return file's uuid
     * @throws IOException
     */
    public String sendVideoToAnalyze(MultipartFile file, String md5Value) throws IOException {
        InputStream inputStream = file.getInputStream();
        // String md5Value = SecureUtil.md5(inputStream);
        inputStream.close();

        // TODO check if video with same md5 value exists and return null string
//        if (sysVideoService.selectSysVideoByMD5(md5Value) != null)
//        {
//            return Result.error(1, "File already exist");
//        }

        String fileUUID = IdUtil.fastSimpleUUID();

        // TODO check if generated uuid exists
//        while (sysVideoService.selectSysVideoByUUID(fileUUID) != null) {
//            fileUUID = IdUtil.fastSimpleUUID();
//        }

        String extension = FilenameUtils.getExtension(file.getOriginalFilename());

        VideoFileMeta videoFileMeta = new VideoFileMeta();
        videoFileMeta.localFileName = fileUUID + "." + extension;
        videoFileMeta.originalFileName = file.getOriginalFilename();
        videoFileMeta.uuid = fileUUID;
        videoFileMeta.md5 = md5Value;

        storageService.store(file, videoFileMeta);

        VideoAnalyzeInfo analyzeInfo = new VideoAnalyzeInfo();
//        analyzeInfo.setId(insertedVideo.getId()); // TODO maybe id is not needed ?
        analyzeInfo.setMeta(videoFileMeta);

        // send to analyze message queue
        rabbitTemplate.convertAndSend(vibraQueue.getName(), analyzeInfo);
        rabbitTemplate.convertAndSend(shenshiQueue.getName(), analyzeInfo);

        return fileUUID;
    }
}
